import React, { useRef, useState } from 'react'
import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from 'antd-mobile'
import classNames from 'classnames'
import {
  getUserProfile,
  updateUserPhoto,
  updateUserProfile
} from '@/store/actions/profile'
import styles from './index.module.scss'
import useInitState from '@/utils/hooks'

import EditInput from './EditInput'
import { useDispatch } from 'react-redux'
import EditList from './EditList'
import dayjs from 'dayjs'
import { logout } from '@/store/actions/login'
import { useHistory } from 'react-router'

const Item = List.Item
// 关闭弹层
const ProfileEdit = () => {
  const history = useHistory()
  const fileRef = useRef<HTMLInputElement>(null)
  const dispatch = useDispatch()
  type ListState = { visible: boolean; type: '' | 'gender' | 'photo' }
  const [showList, setShowList] = useState<ListState>({
    visible: false,
    type: ''
  })
  const [showInput, setShowInput] = useState<InputState>({
    type: '',
    visible: false
  })
  const hideList = () =>
    setShowList({
      type: '',
      visible: false
    })
  const hideInput = () => {
    setShowInput({
      type: '',
      visible: false
    })
  }
  type InputState = {
    visible: boolean
    type: '' | 'name' | 'intro'
  }

  const onUpdate = async (key: string, value: string) => {
    console.log(key, value)
    if (key === 'photo') {
      fileRef.current!.click()
      return
    }

    await dispatch(updateUserProfile(key, value))
    Toast.show({
      icon: 'success',
      content: '修改成功'
    })
    hideInput()
    hideList()
  }

  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files![0]

    if (!file) return
    const photoData = new FormData()

    photoData.append('photo', file)
    await dispatch(updateUserPhoto(photoData))
    hideList()
  }
  const { userProfile } = useInitState(getUserProfile, 'profile')
  const [showBirthday, setShowBirthday] = useState(false)

  const onBirthdayShow = () => {
    setShowBirthday(true)
  }
  const onBirthdayHide = () => {
    setShowBirthday(false)
  }

  const onUpdateBirthday = (value: Date) => {
    const birthday = dayjs(value).format('YYYY-MM-DD')

    onUpdate('birthday', birthday)
    onBirthdayHide()
  }
  const onLogout = () => {
    const handler = Dialog.show({
      title: '温馨提示',
      content: '亲，你确定退出吗？',
      closeOnAction: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            onClick: () => {
              handler.close()
            }
          },
          {
            key: 'confirm',
            text: '退出',
            style: {
              color: 'var(--adm-color-weak)'
            },
            onClick: () => {
              dispatch(logout())
              history.replace('/login')
              Toast.show({ content: '退出成功' })
            }
          }
        ]
      ]
    })
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}>
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={
                      userProfile.photo ||
                      'http://toutiao.itheima.net/images/user_head.jpg'
                    }
                    alt=""
                  />
                </span>
              }
              onClick={() => setShowList({ visible: true, type: 'photo' })}
              arrow>
              头像
            </Item>
            <Item
              arrow
              extra={userProfile.name}
              onClick={() => setShowInput({ visible: true, type: 'name' })}>
              昵称
            </Item>
            <Item
              arrow
              onClick={() => setShowInput({ visible: true, type: 'intro' })}
              extra={
                <span className={classNames('intro', 'normal')}>
                  {userProfile.intro || '未填写'}
                </span>
              }>
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={userProfile.gender === 0 ? '男' : '女'}
              onClick={() => setShowList({ visible: true, type: 'gender' })}>
              性别
            </Item>
            <Item arrow extra={userProfile.birthday} onClick={onBirthdayShow}>
              生日
            </Item>
            <DatePicker
              visible={showBirthday}
              value={new Date(userProfile.birthday)}
              onCancel={onBirthdayHide}
              onConfirm = {onUpdateBirthday }
              title="选择年月日"
              min={new Date(1900, 0, 1, 0, 0, 0)}
              max={new Date()}
            />
          </List>

        </div>
      </div>
      <input
        type="file"
        hidden
        ref={fileRef}
        onChange={(e) => {
          onChangePhoto(e)
        }}
      />
      <Popup visible={showList.visible}>
        <EditList
          type={showList.type}
          hideList={hideList}
          onUpdate={onUpdate}
        />
      </Popup>
      <Popup visible={showInput.visible} position="right" destroyOnClose>
        <EditInput
          onUpdate={onUpdate}
          hideInput={hideInput}
          type={showInput.type}
        />
      </Popup>
      <div className="logout">
        <Button onClick={onLogout} className="btn">退出登录</Button>
      </div>
    </div>
  )
}

export default ProfileEdit
